<?php

/**
 * This is the model class for table "Gadata".
 *
 * The followings are the available columns in table 'Gadata':
 * @property string $id
 * @property string $landing_page
 * @property string $page_title
 * @property integer $page_views
 * @property integer $visits
 * @property integer $visitors
 * @property integer $bounce_rate
 * @property string $pageviews_per_visit
 * @property string $time_on_page
 * @property string $avg_time_on_page
 * @property integer $day
 * @property integer $month
 * @property string $year
 * @property integer $hour
 */
class Gadata extends CActiveRecord
{

    public $up_status;
    public $margin;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Gadata the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'Gadata';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('landing_page, page_title, page_views, visits, visitors, bounce_rate, pageviews_per_visit, time_on_page, avg_time_on_page, day, month, year, hour', 'required'),
            array('page_views, visits, visitors, bounce_rate, day, month, hour', 'numerical', 'integerOnly' => true),
            array('landing_page', 'length', 'max' => 1500),
            array('page_title', 'length', 'max' => 1000),
            array('pageviews_per_visit, time_on_page, avg_time_on_page', 'length', 'max' => 10),
            array('year', 'length', 'max' => 3),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, landing_page, page_title, page_views, visits, visitors, bounce_rate, pageviews_per_visit, time_on_page, avg_time_on_page, day, month, year, hour', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'landing_page' => 'Landing Page',
            'page_title' => 'Page Title',
            'page_views' => 'Page Views',
            'visits' => 'Visits',
            'visitors' => 'Visitors',
            'bounce_rate' => 'Bounce Rate',
            'pageviews_per_visit' => 'Pageviews Per Visit',
            'time_on_page' => 'Time On Page',
            'avg_time_on_page' => 'Avg Time On Page',
            'day' => 'Day',
            'month' => 'Month',
            'year' => 'Year',
            'hour' => 'Hour',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id, true);
        $criteria->compare('landing_page', $this->landing_page, true);
        $criteria->compare('page_title', $this->page_title, true);
        $criteria->compare('page_views', $this->page_views);
        $criteria->compare('visits', $this->visits);
        $criteria->compare('visitors', $this->visitors);
        $criteria->compare('bounce_rate', $this->bounce_rate);
        $criteria->compare('pageviews_per_visit', $this->pageviews_per_visit, true);
        $criteria->compare('time_on_page', $this->time_on_page, true);
        $criteria->compare('avg_time_on_page', $this->avg_time_on_page, true);
        $criteria->compare('day', $this->day);
        $criteria->compare('month', $this->month);
        $criteria->compare('year', $this->year, true);
        $criteria->compare('hour', $this->hour);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    private function _getAnalystCriteria($numPrevDay = 1)
    {
        $criteria = new CDbCriteria();
        $criteria->addCondition('day=:day');
        $criteria->addCondition('month=:month');
        $criteria->addCondition('year=:year');

        $today = strtotime("today 00:00");
        $yesterday = strtotime("-$numPrevDay day", $today);

        $day = date('d', $yesterday);
        $month = date('m', $yesterday);
        $year = date('Y', $yesterday);

        $params = array(
            ':day' => $day,
            ':month' => $month,
            ':year' => $year
        );

        //print_r($params);die();

        $criteria->params = $params;
        return $criteria;
    }

    public function getTop30ByPageviews()
    {
        $criteria = $this->_getAnalystCriteria();
        $criteria->select = "id,rank, landing_page, page_title, page_views, bounce_rate";
        $criteria->order = "page_views desc";
        $criteria->limit = 30;
        //$criteria->distinct = true;
        return $this->findAll($criteria);
    }

    public function getHistoryByPage($landing_page, $page_title)
    {
        $criteria = new CDbCriteria();
        $criteria->compare('landing_page', $landing_page);
        $criteria->compare('page_title', $page_title);
        $criteria->order = "id desc";
        $criteria->group = "day, month, year";
        $criteria->limit = 30;
        return $this->findAll($criteria);
    }

    public function getPreviousTop30Landingpage($pages)
    {
        $criteria = $this->_getAnalystCriteria(2);
        $criteria->select = "id,rank, landing_page, page_title, page_views, bounce_rate";
        $criteria->addInCondition('landing_page', $pages);
        $criteria->order = "page_views desc";
        //$criteria->distinct = true;
        $criteria->limit = 30;
        return $this->findAll($criteria);
    }

    public function getDataProvider()
    {
        $criteria = $this->_getAnalystCriteria();

        $dataProvider = new CActiveDataProvider('Gadata', array(
                    'criteria' => $criteria
                ));
        return $dataProvider;
    }

    public function getReportData()
    {
        $criteria = $this->_getAnalystCriteria();
        $criteria->order = "page_views desc";
        $criteria->limit = 30;

        $result = $this->findAll($criteria);

        $pageviews_per_visit = array();
        $time_on_page = array();
        $avg_time_on_page = array();
        $page_views = array();

        foreach ($result as $row) {
            $pageviews_per_visit[] = $row->pageviews_per_visit;
            //$time_on_page[] = $row->time_on_page;
            $avg_time_on_page[] = $row->avg_time_on_page;
            $page_views[] = $row->page_views;
        }

        $bar1 = "[" . implode($pageviews_per_visit, ",") . "]";
        $bar2 = "[" . implode($time_on_page, ",") . "]";
        $bar3 = "[" . implode($avg_time_on_page, ",") . "]";
        $bar4 = "[" . implode($page_views, ",") . "]";

        $data = $bar1 . "," . $bar2 . "," . $bar3 . "," . $bar4;
        return $data;
    }

    public function categorizeURLs($data)
    {
        
    }

    public function getVisualizeJson()
    {
        $criteria = $this->_getAnalystCriteria();
        $criteria->group = "landing_page";
        //$criteria->addCondition("page_views>10");
        $criteria->order = "page_views desc";
        $criteria->limit = 30;
        $result = $this->findAll($criteria);
        $json = ' {"name": "Terve Media",';
        $json .= ' "children": [';
        $categories = array();
        $childjson = array();

        foreach ($result as $row) {
            $segment = explode('/', $row->landing_page);
            $category = $segment[1];
            $categories[$category][] = "{" . '"name":"' . str_replace('| Terve.fi', '', htmlspecialchars($row->page_title)) . '","size":"' . $row->page_views . '"}';
        }

        foreach ($categories as $key => $value) {
            $subjson = ' {"name": "' . str_replace(array('-', '=', '?', '"'), '', htmlspecialchars($key)) . '",';
            $subjson .='"children": [';
            $subjson .= implode($value, ",");
            $subjson .= '  ]}';
            $childjson[] = $subjson;
        }
        $json .= implode($childjson, ",");
        $json .= '  ]}';

        return $json;
    }

}